import React, { useState, useMemo } from 'react';
import { Table, Input, Button, Space } from 'antd';
import { SearchOutlined, ReloadOutlined, ExportOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import type { ColumnsType, TableProps } from 'antd/es/table';

interface DataTableColumn {
  key: string;
  title: string;
  dataIndex: string;
  width?: number;
  searchable?: boolean;
  sortable?: boolean;
  render?: (value: any, record: any) => React.ReactNode;
}

interface ThemedDataTableProps<T> {
  columns: DataTableColumn[];
  data: T[];
  loading?: boolean;
  onRefresh?: () => void;
  onExport?: () => void;
  searchPlaceholder?: string;
  className?: string;
  size?: 'small' | 'middle' | 'large';
  showRefresh?: boolean;
  showExport?: boolean;
  showSearch?: boolean;
  rowSelection?: TableProps<T>['rowSelection'];
  onRow?: TableProps<T>['onRow'];
}

function ThemedDataTable<T extends Record<string, any>>({
  columns,
  data,
  loading = false,
  onRefresh,
  onExport,
  searchPlaceholder,
  className,
  size = 'small', // 默认使用小尺寸以缩小行间距
  showRefresh = true,
  showExport = true,
  showSearch = true,
  rowSelection,
  onRow,
}: ThemedDataTableProps<T>) {
  const { t } = useTranslation();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [searchText, setSearchText] = useState('');

  // 过滤数据
  const filteredData = useMemo(() => {
    if (!searchText) return data;
    
    return data.filter(record =>
      columns
        .filter(col => col.searchable !== false)
        .some(col => {
          const value = record[col.dataIndex];
          return value && 
            value.toString().toLowerCase().includes(searchText.toLowerCase());
        })
    );
  }, [data, searchText, columns]);

  // 转换列配置
  const antdColumns: ColumnsType<T> = useMemo(() => {
    return columns.map(col => ({
      key: col.key,
      title: col.title,
      dataIndex: col.dataIndex,
      width: col.width,
      sorter: col.sortable ? (a: T, b: T) => {
        const aVal = a[col.dataIndex];
        const bVal = b[col.dataIndex];
        if (typeof aVal === 'string' && typeof bVal === 'string') {
          return aVal.localeCompare(bVal);
        }
        return aVal - bVal;
      } : undefined,
      render: col.render,
    }));
  }, [columns]);

  return (
    <div 
      className={className}
      style={{
        background: `linear-gradient(135deg, ${theme.cardBackground} 0%, ${theme.cardBackground}ee 100%)`,
        borderRadius: '16px',
        border: `1px solid ${theme.cardBorder}`,
        boxShadow: theme.cardShadow,
        overflow: 'hidden',
        backdropFilter: 'blur(10px)',
        position: 'relative',
        padding: '24px',
      }}
    >
      {/* 工具栏 */}
      <div style={{ 
        marginBottom: 16, 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div>
          {showSearch && (
            <Input
              placeholder={searchPlaceholder || t('common.search')}
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ 
                width: 300,
                background: mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)',
                borderColor: theme.cardBorder,
                color: theme.textPrimary,
                borderRadius: '8px'
              }}
              allowClear
            />
          )}
        </div>
        
        <Space>
          {showRefresh && (
            <Button
              icon={<ReloadOutlined />}
              onClick={onRefresh}
              disabled={loading}
              style={{
                background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)',
                borderColor: theme.cardBorder,
                color: theme.textPrimary,
                borderRadius: '8px'
              }}
            >
              {t('common.refresh')}
            </Button>
          )}
          
          {showExport && (
            <Button
              icon={<ExportOutlined />}
              onClick={onExport}
              disabled={loading || filteredData.length === 0}
              style={{
                background: mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)',
                borderColor: theme.cardBorder,
                color: theme.textPrimary,
                borderRadius: '8px'
              }}
            >
              {t('common.export')}
            </Button>
          )}
        </Space>
      </div>

      {/* 表格 */}
      <Table<T>
        columns={antdColumns}
        dataSource={filteredData}
        loading={loading}
        size={size}
        rowSelection={rowSelection}
        onRow={onRow}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            t('common.pagination.total', { 
              start: range[0], 
              end: range[1], 
              total 
            }),
          pageSizeOptions: ['10', '20', '50', '100'],
          defaultPageSize: 20,
        }}
        scroll={{ x: true }}
        style={{
          background: 'transparent',
          borderRadius: '8px'
        }}
        // 自定义表格样式以支持主题
        rowClassName={() => mode === 'dark' ? 'table-row-dark' : 'table-row-light'}
      />
      
      {/* 自定义样式 */}
      <style>{`
        .table-row-dark:hover td {
          background: rgba(255, 255, 255, 0.05) !important;
        }
        
        .table-row-light:hover td {
          background: rgba(0, 0, 0, 0.05) !important;
        }
        
        .ant-table {
          background: transparent !important;
        }
        
        .ant-table-thead > tr > th {
          background: ${mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'} !important;
          color: ${theme.textPrimary} !important;
          border-bottom: 1px solid ${theme.cardBorder} !important;
        }
        
        .ant-table-tbody > tr > td {
          background: transparent !important;
          color: ${theme.textPrimary} !important;
          border-bottom: 1px solid ${theme.cardBorder} !important;
          padding: 8px 16px !important; /* 缩小行间距 */
        }
        
        .ant-table-tbody > tr:last-child > td {
          border-bottom: none !important;
        }
        
        .ant-table-pagination {
          color: ${theme.textPrimary} !important;
        }
        
        .ant-pagination-item {
          background: ${mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'} !important;
          border: 1px solid ${theme.cardBorder} !important;
        }
        
        .ant-pagination-item a {
          color: ${theme.textPrimary} !important;
        }
        
        .ant-pagination-item-active {
          background: ${theme.glowColor} !important;
          border-color: ${theme.glowColor} !important;
        }
        
        .ant-pagination-item-active a {
          color: white !important;
        }
        
        .ant-pagination-prev, .ant-pagination-next {
          color: ${theme.textPrimary} !important;
        }
        
        .ant-pagination-options {
          color: ${theme.textPrimary} !important;
        }
        
        .ant-select-selector {
          background: ${mode === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'} !important;
          border: 1px solid ${theme.cardBorder} !important;
          color: ${theme.textPrimary} !important;
        }
        
        .ant-select-arrow {
          color: ${theme.textPrimary} !important;
        }
      `}</style>
    </div>
  );
}

export default ThemedDataTable;